//
//  WPUserInfoViewController.m
//  ZhongChouPingTai
//
//  Created by WeiPan on 16/3/30.
//  Copyright © 2016年 WPJoe. All rights reserved.
//

#import "WPUserInfoViewController.h"
#import "ImageHandle.h"
#import "WPSafeViewController.h"
#import "WPUserInfoViewModel.h"
#import "UserModelArchiver.h"


static NSString *const kUITableViewCellIdentifier = @"cellIdentifier";

@interface WPUserInfoViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UIView * redBackView;/**< 头像红色背景图 */
@property (nonatomic, strong) UIImageView * headImageView;/**< 头像 */
@property (nonatomic, strong) UILabel * nameLabel;/**< 名字 */
@property (nonatomic, strong) UIButton * loginBtn;/**< 登录按钮 */
@property (nonatomic, strong) UIButton * registerBtn;/**< 注册按钮 */
@property (nonatomic, strong) UIImageView * arrowImageView;/**< 箭头 */

@property (nonatomic, strong) UIButton * attentionBtn;/**< 我的关注 */
@property (nonatomic, strong) UIButton * moneyBtn;/**< 我的资金 */
@property (nonatomic, strong) UIButton * orderBtn;/**< 我的订单 */
@property (nonatomic, strong) UIImagePickerController * imagePickerVC;/**< 图片拾取 */
@property (nonatomic, assign) UIImagePickerControllerSourceType imageSource;/**< 图片来源 */
@property (nonatomic, strong) UITableView * setTableView;/**< 设置表格视图 */
@property (nonatomic, strong) NSArray * setArray;/**< 设置数据源 */
@property (nonatomic, strong) NSArray * nextVCArray;/**< 下一界面控制器数组 */
- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
- (void)refreshData;/**< 刷新数据 */


@end

@implementation WPUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    if (![UserModel defaultUser].needAutoLogin) {
        if (self.nameLabel.superview) {
            [self.nameLabel removeFromSuperview];
        }
        if (self.arrowImageView.superview) {
            [_arrowImageView removeFromSuperview];
        }
        if (!self.loginBtn.superview) {
            [self.redBackView addSubview:self.loginBtn];
            [_redBackView addSubview:self.registerBtn];
        }
        NSString * balanceTitle = [NSString stringWithFormat:@"¥ 0\n我的资金"];
        NSString * orderCount = [NSString stringWithFormat:@"0\n我的订单"];
        [self.moneyBtn setTitle:balanceTitle forState:UIControlStateNormal];
        [self.orderBtn setTitle:orderCount forState:UIControlStateNormal];
    } else {
        [self refreshData];
        if (self.loginBtn.superview) {
            [_loginBtn removeFromSuperview];
            [_registerBtn removeFromSuperview];
        }
        if (!self.nameLabel.superview) {
            [self.redBackView addSubview:_nameLabel];
            _nameLabel.text = [NSString stringWithFormat:@"%@****%@", [[UserModel defaultUser].phoneNumber substringToIndex:3], [[UserModel defaultUser].phoneNumber substringWithRange:NSMakeRange(7, 4)]];
            [_redBackView addSubview:self.arrowImageView];
        }
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark - init
- (void)initializeDataSource {
    self.setArray = @[@[@[@"权益管理.png", @"权益管理"],
                        @[@"转让管理", @"转让管理"],
                        @[@"竞拍管理.png", @"竞拍管理"]],
                      @[@[@"支持项目.png", @"支持项目"],
                        @[@"一元夺宝MyInfo.png", @"一元夺宝"],
                        @[@"项目管理.png", @"项目管理"]],
                      @[@[@"我的消息.png", @"我的消息"],
                        @[@"我的论坛.png", @"我的论坛"],
                        @[@"购物车.png", @"购物车"]],
                      @[@[@"帮助与反馈.png", @"帮助与反馈"],
                        @[@"关于我们-1.png", @"关于我们"]]];
    self.nextVCArray = @[@[@"WPRightManagerViewController",
                              @"WPTransferViewController",
                              @"WPAuctionViewController"],
                            @[@"WPSupportViewController",
                              @"WPMyOnePayViewController",
                              @"WPProjectManagerViewController"],
                            @[@"WPMyMsgViewController",
                              @"WPMyForumViewController",
                              @"WPShopCartViewController"],
                            @[@"WPHelpViewController",
                              @"WPAbountUsViewController"]];
}
- (void)initializeUserInterface {
    [self.view addSubview:self.redBackView];
    [self.redBackView addSubview:self.headImageView];
    [self.view addSubview:self.attentionBtn];
    [self.view addSubview:self.moneyBtn];
    [self.view addSubview:self.orderBtn];
    [self.view addSubview:self.setTableView];
}
#pragma mark - responds events
- (void)respondsToRedbackViewTap {
    if (![UserModel defaultUser].needAutoLogin) {
        return;
        
    }
    WPSafeViewController * vc = [WPSafeViewController new];
    vc.nickName = _nameLabel.text;
    vc.phone = _nameLabel.text;
    [self pushToNextController:vc withVCTitle:@"账户与安全"];
}
- (void)respondsToLoginBtn {
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:[[NSClassFromString(@"WPPwdLoginViewController") alloc]init]];
    [self.tabBarController presentViewController:nav animated:YES completion:nil];
}
- (void)respondsToRegisterBtn {
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:[[NSClassFromString(@"WPRegisterViewController") alloc]init]];
    [self.tabBarController presentViewController:nav animated:YES completion:nil];
}
- (void)respondsToAttenionBtn {
    [self pushToNextController:[[NSClassFromString(@"WPAttentionViewController") alloc]init] withVCTitle:@"我的关注"];
}
- (void)respondsToMoneyBtn {
    [self pushToNextController:[[NSClassFromString(@"WPMoneyViewController") alloc]init] withVCTitle:@"我的资金"];
}
- (void)respondsTOrderBtn {
    [self pushToNextController:[[NSClassFromString(@"WPOrderViewController") alloc]init] withVCTitle:@"我的订单"];
}
#pragma mark- 刷新数据
- (void)refreshData {
    if ([UserModel defaultUser].userID) {
        [WPUserInfoViewModel refreshUserDataWithSuccessBlock:^(NSArray *resultArr) {
            if ([resultArr[0] floatValue] >= 0) {
                NSString * balanceTitle = [NSString stringWithFormat:@"¥%@\n我的资金", resultArr[0]];
                NSString * orderTitle = [NSString stringWithFormat:@"%@\n我的订单", resultArr[1]];
                [_moneyBtn setTitle:balanceTitle forState:UIControlStateNormal];
                [_orderBtn setTitle:orderTitle forState:UIControlStateNormal];
                [UserModel defaultUser].balance = resultArr[0];
                [UserModelArchiver archiver];
            }
        } andWithFailureBlcok:^(NSString *fail) {
            
        }];
        [WPUserInfoViewModel refreshMsgCountWithSuccessBlock:^(NSString *result) {
            UITableViewCell * cell = [_setTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
            for (UIView * view  in cell.contentView.subviews) {
                [view removeFromSuperview];
            }
            [cell.contentView addSubview:cell.textLabel];
            [cell.contentView addSubview:cell.imageView];
            if (![result isEqualToString:@"0"]) {
                CGRect rect = [WPCalculateRectHandle calculateSizeWithFont:10*DHFlexibleHorizontalMutiplier() Text:result height:15*DHFlexibleHorizontalMutiplier()];
                rect.size.width += 10*DHFlexibleHorizontalMutiplier();
                UILabel * numLabel = [[UILabel alloc]initWithFrame:CGRectMake(290*DHFlexibleHorizontalMutiplier() - rect.size.width, 15*DHFlexibleHorizontalMutiplier(), rect.size.width, 15*DHFlexibleHorizontalMutiplier())];
                numLabel.layer.cornerRadius = 7.5*DHFlexibleHorizontalMutiplier();
                numLabel.backgroundColor = COLOR_RGB(234, 27, 47, 1);
                numLabel.textAlignment = NSTextAlignmentCenter;
                numLabel.layer.masksToBounds = YES;
                numLabel.textColor = [UIColor whiteColor];
                numLabel.font = [UIFont systemFontOfSize:10*DHFlexibleHorizontalMutiplier()];
                numLabel.text = result;
                [cell.contentView addSubview:numLabel];
            }
            
        } andWithFailureBlock:^(NSString *fail) {
            
        }];
    }
}
- (void)UesrImageClicked {
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"头像设置" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    __weak typeof(self)weakself = self;
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        weakself.imageSource = UIImagePickerControllerSourceTypePhotoLibrary;
        weakself.imagePickerVC.sourceType = weakself.imageSource;
        [weakself presentViewController:weakself.imagePickerVC animated:YES completion:nil];
    }];;
    UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        weakself.imageSource = UIImagePickerControllerSourceTypeCamera;
        weakself.imagePickerVC.sourceType = weakself.imageSource;
        [weakself presentViewController:weakself.imagePickerVC animated:YES completion:nil];
    }];
    UIAlertAction *imageAction = [UIAlertAction actionWithTitle:@"从图库选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        weakself.imageSource = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        weakself.imagePickerVC.sourceType = weakself.imageSource;
        [weakself presentViewController:weakself.imagePickerVC animated:YES completion:nil];
        
    }];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:deleteAction];
    [alertVC addAction:imageAction];
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [alertVC addAction:archiveAction];
    }
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    UIImage * showImage = [ImageHandle imageWithImageSimple:image scaledToSize:DHFlexibleSize(CGSizeMake(160, 160), YES)];
    _headImageView.image = showImage;
    NSData * data = [NSData data];
    if (UIImagePNGRepresentation(showImage)) {
        //返回为png图像。
        data = UIImagePNGRepresentation(showImage);
    }
    else {
        //返回为JPEG图像。
        data = UIImageJPEGRepresentation(showImage, 1.0);
    }
    if (data.bytes == 0) {
        [self initializeAlertControllerWithMessageAndDismiss:@"目前仅支持jpg/png格式的图片"];
        return;
    }
    [ImageHandle saveImage:showImage WithName:@"headImage.png"];
    
}
#pragma mark - 协议UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _setArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_setArray[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kUITableViewCellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kUITableViewCellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.imageView.image = IMAGE_NAME(_setArray[indexPath.section][indexPath.row][0]);
    cell.textLabel.text = _setArray[indexPath.section][indexPath.row][1];
    ((UILabel *)[cell viewWithTag:250]).text = @"4";
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45*DHFlexibleHorizontalMutiplier();
}
//用户点击了某一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (![UserModel defaultUser].needAutoLogin) {
        [self presentToLoginViewController];
        return;
    }
    Class class = NSClassFromString(_nextVCArray[indexPath.section][indexPath.row]);
    [self pushToNextController:[[class alloc]init] withVCTitle:_setArray[indexPath.section][indexPath.row][1]];
    
}
#pragma mark - getter
- (UIView *)redBackView {
    if (!_redBackView) {
        _redBackView = ({
            UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, 140*DHFlexibleHorizontalMutiplier())];
            view.backgroundColor = COLOR_RGB(234, 27, 47, 1);
            UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(respondsToRedbackViewTap)];
            [view addGestureRecognizer:ges];
            view;
        });
    }
    return _redBackView;
}
- (UIImageView *)headImageView {
    if (!_headImageView) {
        _headImageView = ({
            UIImageView * view = [[UIImageView alloc]initWithFrame:CGRectMake(30*DHFlexibleHorizontalMutiplier(), 30*DHFlexibleHorizontalMutiplier(), 60*DHFlexibleHorizontalMutiplier(), 60*DHFlexibleHorizontalMutiplier())];
            view.layer.cornerRadius = 30*DHFlexibleHorizontalMutiplier();
            view.layer.borderColor = [UIColor whiteColor].CGColor;
            view.layer.borderWidth = 2;
            view.layer.masksToBounds = YES;
            UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(UesrImageClicked)];
            [view addGestureRecognizer:ges];
            view.userInteractionEnabled = YES;
            view.image = [ImageHandle readImageWithImageName:@"headImage.png"].bytes ? [UIImage imageWithData:[ImageHandle readImageWithImageName:@"headImage.png"]] :  IMAGE_NAME(@"morentouxiang.png");
            view;
        });
    }
    return _headImageView;
}
- (UIButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = ({
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.bounds = CGRectMake(0, 0, 50*DHFlexibleHorizontalMutiplier(), 25*DHFlexibleHorizontalMutiplier());
            btn.center = CGPointMake(CGRectGetMaxX(self.headImageView.frame) +40*DHFlexibleHorizontalMutiplier() , self.headImageView.center.y);
            btn.layer.cornerRadius = 3*DHFlexibleHorizontalMutiplier();
            btn.backgroundColor = [UIColor whiteColor];
            btn.titleLabel.font = [UIFont systemFontOfSize:12*DHFlexibleHorizontalMutiplier()];
            [btn setTitle:@"登陆" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(respondsToLoginBtn) forControlEvents:UIControlEventTouchUpInside];
            btn;
        });
    }
    return _loginBtn;
}
- (UIButton *)registerBtn {
    if (!_registerBtn) {
        _registerBtn = ({
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.bounds = CGRectMake(0, 0, 50*DHFlexibleHorizontalMutiplier(), 25*DHFlexibleHorizontalMutiplier());
            btn.center = CGPointMake(CGRectGetMaxX(self.loginBtn.frame) +40*DHFlexibleHorizontalMutiplier() , self.headImageView.center.y);
            btn.layer.cornerRadius = 3*DHFlexibleHorizontalMutiplier();
            btn.backgroundColor = [UIColor whiteColor];
            btn.titleLabel.font = [UIFont systemFontOfSize:12*DHFlexibleHorizontalMutiplier()];
            [btn setTitle:@"注册" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(respondsToRegisterBtn) forControlEvents:UIControlEventTouchUpInside];
            btn;
        });
    }
    return _registerBtn;
}
- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = ({
            UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.headImageView.frame)+20*DHFlexibleHorizontalMutiplier(), CGRectGetMidY(self.headImageView.bounds)+20*DHFlexibleHorizontalMutiplier(), 180*DHFlexibleHorizontalMutiplier(), 30*DHFlexibleHorizontalMutiplier())];
            lab.textColor = [UIColor whiteColor];
            lab.font = [UIFont systemFontOfSize:18*DHFlexibleHorizontalMutiplier()];
            lab.text = [NSString stringWithFormat:@"%@****%@", [[UserModel defaultUser].phoneNumber substringToIndex:3], [[UserModel defaultUser].phoneNumber substringWithRange:NSMakeRange(7, 4)]];
            lab;
        });
    }
    return _nameLabel;
}
- (UIButton *)attentionBtn {
    if (!_attentionBtn) {
        _attentionBtn = ({
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(0, CGRectGetMaxY(self.redBackView.frame) - 40*DHFlexibleVerticalMutiplier(), 107*DHFlexibleHorizontalMutiplier(), 40*DHFlexibleVerticalMutiplier());
            [btn addTarget:self action:@selector(respondsToAttenionBtn) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitle:@"0\n我的关注" forState:UIControlStateNormal];
            btn.titleLabel.numberOfLines = 2;
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            btn.titleLabel.font = [UIFont systemFontOfSize:12*DHFlexibleVerticalMutiplier()];
            btn.layer.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
            btn.alpha = 1;
            UIView * line = [[UIView alloc]initWithFrame:CGRectMake(106*DHFlexibleHorizontalMutiplier(), 10*DHFlexibleHorizontalMutiplier(), 1, 20*DHFlexibleHorizontalMutiplier())];
            line.backgroundColor = COLOR_RGB(220, 88, 88, 1);
            [btn addSubview:line];
            btn;
        });
    }
    return _attentionBtn;
}
- (UIButton *)moneyBtn {
    if (!_moneyBtn) {
        _moneyBtn = ({
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(107*DHFlexibleHorizontalMutiplier(), CGRectGetMaxY(self.redBackView.frame) - 40*DHFlexibleVerticalMutiplier(), 107*DHFlexibleHorizontalMutiplier(), 40*DHFlexibleVerticalMutiplier());
            NSString * title = [NSString stringWithFormat:@"¥%@\n我的资金", [UserModel defaultUser].balance];
            [btn setTitle:title forState:UIControlStateNormal];
            btn.titleLabel.numberOfLines = 2;
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            btn.titleLabel.font = [UIFont systemFontOfSize:12*DHFlexibleVerticalMutiplier()];
            btn.layer.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
            btn.alpha = 1;
            UIView * line = [[UIView alloc]initWithFrame:CGRectMake(106*DHFlexibleHorizontalMutiplier(), 10*DHFlexibleHorizontalMutiplier(), 1, 20*DHFlexibleHorizontalMutiplier())];
            line.backgroundColor = COLOR_RGB(220, 88, 88, 1);
            [btn addSubview:line];
            [btn addTarget:self action:@selector(respondsToMoneyBtn) forControlEvents:UIControlEventTouchUpInside];
            btn;
        });
    }
    return _moneyBtn;
}
- (UIButton *)orderBtn {
    if (!_orderBtn) {
        _orderBtn = ({
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(214*DHFlexibleHorizontalMutiplier(), CGRectGetMaxY(self.redBackView.frame) - 40*DHFlexibleVerticalMutiplier(), 106*DHFlexibleHorizontalMutiplier(), 40*DHFlexibleVerticalMutiplier());
            [btn setTitle:@"0\n我的订单" forState:UIControlStateNormal];
            btn.titleLabel.numberOfLines = 2;
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            btn.titleLabel.font = [UIFont systemFontOfSize:12*DHFlexibleVerticalMutiplier()];
            [btn addTarget:self action:@selector(respondsTOrderBtn) forControlEvents:UIControlEventTouchUpInside];
            btn.layer.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
            btn.alpha = 1;
            btn;
        });
    }
    return _orderBtn;
}
- (UIImageView *)arrowImageView {
    if (!_arrowImageView) {
        _arrowImageView = ({
            UIImageView * view = [[UIImageView alloc]initWithFrame:CGRectMake(295*DHFlexibleHorizontalMutiplier(), 55.5*DHFlexibleHorizontalMutiplier(), 5*DHFlexibleHorizontalMutiplier(), 9*DHFlexibleHorizontalMutiplier())];
            view.image = IMAGE_NAME(@"iconfont-xiala410");
            view;
        });
    }
    return _arrowImageView;
}
- (UIImagePickerController *)imagePickerVC {
    if (!_imagePickerVC) {
        _imagePickerVC = [[UIImagePickerController alloc]init];
        _imagePickerVC.delegate = self;
        _imagePickerVC.allowsEditing = YES;
        _imagePickerVC.sourceType = self.imageSource;
    }
    return _imagePickerVC;
}
- (UITableView *)setTableView {
    if (!_setTableView) {
        _setTableView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.redBackView.frame), SCREEN_SIZE.width, SCREEN_SIZE.height - CGRectGetMaxY(self.redBackView.frame)-CGRectGetHeight(self.tabBarController.tabBar.bounds)) style:UITableViewStylePlain];
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.bounces = NO;
            tableview.separatorColor = COLOR_RGB(211, 211, 211, 1);
            tableview;
        });
    }
    return _setTableView;
}
@end
